package com.pc.tas.web.visitAnaylze;

import com.pc.cloud.services.MetricArg;
import com.pc.cloud.services.SearchResults;
import com.pc.cloud.services.SearchServices;
import com.pc.cloud.utils.NamePair;
import com.pc.tas.export.ExportResult;
import com.pc.tas.export.expfilelist.ExpFileList;
import com.pc.tas.learning.trace.index.TraceSearchArgs;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.*;
import java.util.Map.Entry;

@Controller
public class HourAnaylyzeController {
	final public static MathContext mctx = new MathContext(20);
	final public static BigDecimal hundrend = new BigDecimal(100);
	private static final String[] hours_day = new String[] { "00", "01", "02",
			"03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13",
			"14", "15", "16", "17", "18", "19", "20", "21", "22", "23" };

	@Autowired
	private SearchServices searchServices;

	@RequestMapping("/hourAnalyze/trend")
	@ResponseBody
	public String analyze(@RequestParam Map<String,String> params) {
		try{					
			TraceSearchArgs tsa = new TraceSearchArgs();
			Map<String,String> args = new HashMap<String,String>();
			Map<String,String[]> ranges = new HashMap<String,String[]>();
			List<MetricArg> metricFields = new ArrayList<MetricArg>();
			for(Entry<String,String> entry : params.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				if(key.startsWith("filter_")) {			
					if(value!=null && !"null".equals(value)) {
						args.put(key.substring(7), value);
					}					
				}else if(key.startsWith("begin_range_")) {
					String v = value;
					if(v != null && !"null".equals(v)) {
						String k = key.substring(12);
						String[] rs = ranges.get(k);
						if(rs != null) {
							rs[0] = v; 
						} else {
							rs = new String[2];
							rs[0] = v;
							ranges.put(k, rs);
						}
					}					
				} else if(key.startsWith("end_range_")) {
					String v = value;
					if(v != null && !"null".equals(v)) {
						String k = key.substring(10);
						String[] rs = ranges.get(k);
						if(rs != null) {
							rs[1] = v; 
						} else {
							rs = new String[2];
							rs[1] = v;
							ranges.put(k, rs);
						}
					}		
				}
			}
			
			if(args.size() > 0) {
				tsa.setOtherParams(args);
			}

			if(ranges.size() > 0) {
				tsa.setOtherRange(ranges);
			}
			
			MetricArg pv = new MetricArg("pv", MetricArg.DISTINCT_COUNT);
			MetricArg uv = new MetricArg("uv", MetricArg.DISTINCT_COUNT);
			MetricArg ip = new MetricArg("ip", MetricArg.DISTINCT_COUNT);
			MetricArg visits = new MetricArg("id", MetricArg.COUNT);
			MetricArg users = new MetricArg("user-id", MetricArg.DISTINCT_COUNT);
			metricFields.add(pv);
			metricFields.add(uv);
			metricFields.add(ip);
			metricFields.add(visits);
			metricFields.add(users);
			tsa.setType("view");
			JSONArray jitems = new JSONArray();
			List<String> hours = Arrays.asList(hours_day);
			for(String hour : hours){
				tsa.setMetricFields(metricFields);
				tsa.setHour(hour);
				SearchResults res = searchServices.search(tsa);
				this.getSumJSON(res,jitems,hour);
			}
			
			JSONObject result = new JSONObject();
			result.put("records", jitems);
			return result.toString();
		}catch(Throwable e){
			e.printStackTrace();
			return "error:" + e.getMessage();
		}
	}

	private void getSumJSON(SearchResults res, JSONArray jitems,String hour) throws Exception {
		JSONObject jo = new JSONObject();
		jo.put("name", hour);
		Collection<NamePair> sums = res.getSum();
		if(sums != null && sums.size()>0) {
			for(NamePair np : sums) {
				String name = "metric_" + np.getName();
				jo.put(name, np.getValue());
			}
		}
	
		jitems.put(jo);	
	}
	
	@Autowired
	private ExportResult export;
	
	@RequestMapping("/hourAnalyze/export")
	@ResponseBody
	public String export(@RequestParam Map<String,String> params,HttpServletRequest request){
		String fileName = params.get("fileName");
		String column = params.get("column");
		String[] columns = column.split(",");
		
		try{
			JSONArray fields = new JSONArray();
			for(String field : columns){
				JSONObject jo = new JSONObject();
				String[] item = field.split(":");
				jo.put(item[0], item[1]);
				fields.put(jo);
			}
			export.setExpType(ExpFileList.EXP_TYPE_HourAnalyze);
			export.createFile(request, fileName, fields);
			
			String result = this.analyze(params);
            JSONObject res = new JSONObject(result);
            JSONArray jarr = res.getJSONArray("records");
            export.doExport(jarr);
            
			export.close();
			if(!export.isHasData())return "0";
			return "1";
		}catch(Exception e){
			e.printStackTrace();
		}
		return "-1";
	}
	

}
